package cn.chinaunicom.sdsi.activiti.example.common.impl;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import cn.chinaunicom.sdsi.activiti.example.common.ActivitiCommon;

@Component
public class ActivitiCommonImpl implements ActivitiCommon {

	/**
	 * 流程定义管理
	 */
	@Autowired
	private RepositoryService repositoryService;
	
	/**
	 * 流程实例
	 */
	@Autowired
	private RuntimeService runtimeService;
	
	/**
	 * 任务
	 */
	@Autowired
	private TaskService taskService;
	
	/**
	 * 历史数据
	 */
	@Autowired
	private HistoryService historyService;
	
	
	@Override
	public Deployment deployProcess(MultipartFile file, Deployment deployment) {
		InputStream fileInputStream = null;
		try {
			fileInputStream = file.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return repositoryService.createDeployment().key(deployment.getKey()).name(deployment.getName()).tenantId(deployment.getTenantId()).addInputStream(file.getOriginalFilename(),fileInputStream).deploy();
	}

	@Override
	public ProcessInstance startProcess(String processDefinitionKey, String businessKey,
			Map<String, Object> variables) {
		return runtimeService.startProcessInstanceByKey(processDefinitionKey, businessKey,variables);
	}

	@Override
	public void pushProcess(String taskId, String userId, String action, Map<String, Object> variables) {
		
		if("complate".equals(action)) {
			taskService.complete(taskId, variables);
		}else if("claim".equals(action)) {
			taskService.claim(taskId, userId);
		}else if("unclaim".equals(action)) {
			taskService.unclaim(taskId);
		}else if("resolveTask".equals(action)) {
			taskService.resolveTask(taskId);
		}
	}

	@Override
	public List<Task> queryTask(Map<String, Object> map, int start, int length) {
		return taskService.createTaskQuery().taskAssignee(map.get("assignee").toString()).orderByTaskCreateTime().desc().listPage(start, length);
	}

}
